import { Button, Modal, Input } from "antd";
import { useMemo, useState } from "react";
import { createSchemaField, FormProvider } from '@formily/react';
import { createForm } from "@formily/core";
import { FormItem } from "@formily/antd";
import _ from 'lodash';
export interface SchemaCheckProps {
    schema?: any;
}

const SchemaCheck: React.FC<SchemaCheckProps> = ({ schema }) => {
    const form = createForm();

    const SchemaField = createSchemaField({
        components: {
            Input,
            FormItem
        },
    })
    const [visible, setVisible] = useState<boolean>(false);
    const sc: any = useMemo(() => {
        const origin = {
            "type": "object",
            "properties": {
                "__source": {
                    "type": "string",
                    "title": '源',
                    'x-decorator': 'FormItem',
                    "x-component": "Input",
                    "x-reactions": schema
                },
                // "target": {
                //     "title": '目标',
                //     "type": "string",
                //     'x-decorator': 'FormItem',
                //     "x-component": "Input"
                // }
            }
        }
        const schemaControl = () => {
            // 如果存在
            const opSc: any = _.cloneDeep({ ...origin })
            if (schema?.target) {
                opSc.properties.target = {
                    "title": '目标',
                    "type": "string",
                    'x-decorator': 'FormItem',
                    "x-component": "Input"
                }
                return opSc
            } else if (schema?.dependencies?.length > 0) {
                schema?.dependencies?.forEach((key: string, index: number) => {
                    opSc.properties[key] = {
                        "title": key,
                        "type": "string",
                        'x-decorator': 'FormItem',
                        "x-component": "Input"
                    }
                })
                return opSc
            }
        }
        return schemaControl()
    }, [JSON.stringify(schema)])
    console.log('sc', sc)
    return <>
        <Button type="primary" onClick={() => setVisible(true)}>校验</Button>
        <Modal visible={visible} onCancel={() => setVisible(false)} title="协议校验">
            <FormProvider form={form}>
                <SchemaField schema={sc} ></SchemaField>
            </FormProvider>
        </Modal>
    </>
}

export default SchemaCheck;